#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <tchar.h>

int main(int argc, char * argv[]) {
    LPCTSTR filepath = _T("example.txt");
    const char *text = "Hello, mmap!";
    size_t text_size = strlen(text);

    // 创建文件
    HANDLE hFile = CreateFile(
        filepath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );
    
    if (hFile == INVALID_HANDLE_VALUE) {
        _tprintf(_T("无法创建文件，错误代码: %lu\n"), GetLastError());
        return 1;
    }

    // 创建文件映射
    HANDLE hMapping = CreateFileMapping(
        hFile,
        NULL,
        PAGE_READWRITE,
        0,
        text_size,
        NULL
    );
    
    if (!hMapping) {
        _tprintf(_T("无法创建文件映射，错误代码: %lu\n"), GetLastError());
        CloseHandle(hFile);
        return 1;
    }

    // 映射视图
    void *mapped = MapViewOfFile(
        hMapping,
        FILE_MAP_WRITE,
        0,
        0,
        text_size
    );
    
    if (!mapped) {
        _tprintf(_T("无法映射视图，错误代码: %lu\n"), GetLastError());
        CloseHandle(hMapping);
        CloseHandle(hFile);
        return 1;
    }

    // 写入数据
    memcpy(mapped, text, text_size);

    // 取消映射
    UnmapViewOfFile(mapped);
    CloseHandle(hMapping);
    CloseHandle(hFile);

    _tprintf(_T("Windows 内存映射演示成功完成\n"));
    return 0;
}
